package com.website.dayouziblog.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = InformationSchemaDataSourceConfig.PACKAGE, sqlSessionFactoryRef = "informationSchemaSqlSessionFactory")
public class InformationSchemaDataSourceConfig {
    static final String PACKAGE = "com.website.dayouziblog.mapper.informationSchema";
    static final String MAPPER_LOCATION = "classpath:mapper/**/*.xml";

    @Value("${spring.datasource.informationSchema.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.informationSchema.url}")
    private String url;

    @Value("${spring.datasource.informationSchema.username}")
    private String username;

    @Value("${spring.datasource.informationSchema.password}")
    private String password;


    @Bean(name = "informationSchemaDataSource")
    public DataSource informationSchemaDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        return dataSource;
    }

    @Bean(name = "informationSchemaTransactionManager")
    public DataSourceTransactionManager informationSchemaTransactionManager() {
        return new DataSourceTransactionManager(informationSchemaDataSource());
    }

    @Bean(name = "informationSchemaSqlSessionFactory")
    public SqlSessionFactory informationSchemaSqlSessionFactory(@Qualifier("informationSchemaDataSource") DataSource informationSchemaDataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(informationSchemaDataSource);
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources(InformationSchemaDataSourceConfig.MAPPER_LOCATION));
        return sessionFactory.getObject();
    }
}
